var db = require("../util/DataBase.js")

var searchService = require("../service/search.js");

var articleService = {
  getRank(articleId, success, error) {

    db.query("SELECT `rank` FROM `article` WHERE `id` = ?", [
      articleId
    ], function (err, results) {
      if(err) {
        error && error("获取rank失败")
      } else {
        success && success(results[0].rank);
      }
    });

  },
  adjustRank(articleId, inc, success, error) {

    articleService.getRank(
      articleId,
      function (rank) {

        var newRank = rank * 1 + inc;

        db.query("UPDATE article SET `rank` = ? WHERE `id` = ?", [
          newRank,
          articleId
        ], function (err, results) {
          if(err) {
            error && error("更新rank失败")
          } else {
            searchService.updateRank(articleId, inc);
            success && success(newRank);
          }
        });

      },
      function () {
        error && error("获取rank失败");
      }
    );

  },
  isQuestion(articleId, success, error) {
    db.query("SELECT `question` FROM `article` WHERE `id` = ?", [
      articleId
    ], function (err, results) {
      if(err) {
        error && error("获取帖子问题状态失败")
      } else {
        success && success(results[0].question == 1);
      }
    });
  },
  removeAllTopic(articleId, success, error) {

    var values = [
      articleId
    ];

    db.query("DELETE FROM `article_in_topic` WHERE `article_id` = ?", values, function(err, results) {

      if(err)
      {
        error && error(err);
      }
      else
      {
        success && success();
      }

    });

  }
}

module.exports = articleService;
